package com.monkeygroup.mygoplus.view.entrance.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyAlertDialog;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.HttpModel.SimpleOnHttpRequestListener;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.user.vo.PersonalNomalInfo;
import com.monkeygroup.mygoplus.view.entrance.activity.EntranceActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/9.
 */
public class LoginFragment extends Fragment implements View.OnClickListener {
    private View mView;
    private final String TAG = "LoginFragment";

    private Activity activity;
    private Spinner choosespinner;
    private EditText et, pwdEt;
    private TextView tv, pwdTv, btnRegister, txtDirectLogin;


    //头部
    private TextView txtTitle;
    private ImageView imgBack;

    private LinearLayout llReadPwd;
    private ImageView img_read_pwd;


    // Fragment管理对象
    private FragmentManager manager;
    private FragmentTransaction ft;

    //請求參數
    private Map<String, String> params;
    private HttpModel httpModel, validatehttpModel;
    private PersonalNomalInfo vo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mView == null) {

            mView = inflater.inflate(R.layout.fragment_login, container, false);
            manager = getFragmentManager();

            initView();
            initListener();
            initRequest();
        }
        return mView;
    }

    private void initView() {

        activity = this.getActivity();
        txtTitle = (TextView) mView.findViewById(R.id.txt_title);
        txtTitle.setText("Sign In");
        imgBack = (ImageView) mView.findViewById(R.id.img_back);
        imgBack.setVisibility(View.INVISIBLE);

        et = (EditText) mView.findViewById(R.id.et);
        pwdEt = (EditText) mView.findViewById(R.id.pwd_et);
        tv = (TextView) mView.findViewById(R.id.tv);
        pwdTv = (TextView) mView.findViewById(R.id.pwd_tv);
        btnRegister = (TextView) mView.findViewById(R.id.btn_register);


        txtDirectLogin = (TextView) mView.findViewById(R.id.txt_direct_login);
        llReadPwd = (LinearLayout) mView.findViewById(R.id.ll_read_pwd);
        img_read_pwd = (ImageView) mView.findViewById(R.id.img_read_pwd1);

        choosespinner = (Spinner) mView.findViewById(R.id.choosespinner);

        String[] items = getResources().getStringArray(R.array.spingarr);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, R.layout.myspinner, items);
        choosespinner.setAdapter(adapter);

        params = new HashMap<>();

        if (LocalInfo.getLoginInfo(activity) != null) {

            vo = LocalInfo.getLoginInfo(activity);
            if (vo.getName() != null && !"".equals(vo.getName())) {
                tv.setVisibility(View.GONE);
                et.setText(vo.getName());
                img_read_pwd.setImageDrawable(getResources().getDrawable(R.mipmap.bt_login_remem_ok));
            }
            if (vo.getPassword() != null && !"".equals(vo.getPassword())) {
                pwdTv.setVisibility(View.GONE);
                pwdEt.setText(vo.getPassword());
                img_read_pwd.setImageDrawable(getResources().getDrawable(R.mipmap.bt_login_remem_ok));
            }


        }

    }

    private void fillData() {


    }

    private void initListener() {
        mView.findViewById(R.id.btn_login).setOnClickListener(this);
        mView.findViewById(R.id.btn_register).setOnClickListener(this);
        mView.findViewById(R.id.other_login).setOnClickListener(this);
        mView.findViewById(R.id.txt_direct_login).setOnClickListener(this);
        mView.findViewById(R.id.ll_read_pwd).setOnClickListener(this);
        mView.findViewById(R.id.find_pwd).setOnClickListener(this);


        et.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tv.setVisibility(View.VISIBLE);
                } else {
                    tv.setVisibility(View.GONE);

                    boolean isread = img_read_pwd.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.bt_login_remem_no).getCurrent().getConstantState());

                    if (!isread) {
                        //保存密碼
                        vo = new PersonalNomalInfo();
                        vo.setName(String.valueOf(et.getText()));
                        vo.setPassword(String.valueOf(pwdEt.getText()));

                        LocalInfo.saveLoginInfo(activity, vo);
                    }
                }


            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pwdEt.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    pwdTv.setVisibility(View.VISIBLE);
                } else {
                    pwdTv.setVisibility(View.GONE);
                    boolean isread = img_read_pwd.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.bt_login_remem_no).getCurrent().getConstantState());

                    if (!isread) {
                        //保存密碼
                        vo = new PersonalNomalInfo();
                        vo.setName(String.valueOf(et.getText()));
                        vo.setPassword(String.valueOf(pwdEt.getText()));

                        LocalInfo.saveLoginInfo(activity, vo);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    public void initRequest() {

        httpModel = new HttpModel(RequestUrl.baseUrl + RequestUrl.loginUrl, params, new SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (!VilidateUtil.isSuccess(resultCode)) {
                    if (resultCode == 302) {
                        String count = LocalInfo.getLoginCount(activity, String.valueOf(et.getText()));
                        if (count == null || "".equals(count)) {
                            count = "0";
                        }

                        //记录登录次数
                        LocalInfo.saveLoginCount(activity, String.valueOf(et.getText()), count);

                        //Toast.makeText(activity,String.valueOf(et.getText()), Toast.LENGTH_SHORT).show();
                        MyAlertDialog dialog = new MyAlertDialog(activity, resultMsg, String.valueOf(et.getText()));
                        dialog.show(activity, resultMsg, 2);
                    } else {
                        Toast.makeText(activity, resultMsg, Toast.LENGTH_SHORT).show();
                        MyAlertDialog dialog = new MyAlertDialog(activity, "不存在的賬號", String.valueOf(et.getText()));
                        dialog.show(activity, "不存在的賬號", 1);
                    }

                } else {
                    Map<String, String> map = (HashMap) data;
                    MyGoApplication.token = map.get("token");
                    MyGoApplication.myNickname = map.get("username");
                    MyGoApplication.myECUserid = et.getText().toString().trim();
                    doBlockList();

                    //记录登录次数
//                    Log.e("getHeadIcon===",""+((PersonalNomalInfo)data).getHeadIcon());
                    LocalInfo.saveLoginCount(activity, String.valueOf(et.getText()), "-1");
                    vo = new PersonalNomalInfo();
                    vo.setName(String.valueOf(et.getText()));
                    vo.setPassword(String.valueOf(pwdEt.getText()));
                    vo.setUserName(String.valueOf(((Map)data).get("username")));
                    vo.setMobile(String.valueOf(((Map)data).get("mobile")));
                    vo.setGender(String.valueOf(((Map)data).get("username")));
                    vo.setHeadIcon(String.valueOf(((Map)data).get("headIcon")));
                    vo.setBackground(String.valueOf(((Map)data).get("background")));
                    LocalInfo.saveUserInfo(activity,vo);
                }
            }
        }, true);

        validatehttpModel = new HttpModel(RequestUrl.baseUrl + RequestUrl.vilidateUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                Map<String, String> result = (HashMap) data;

                if (Double.parseDouble(String.valueOf(result.get("isSignUp"))) == 0) {

                    MyAlertDialog dialog = new MyAlertDialog(activity, "該手機還沒註冊", String.valueOf(tv.getText()));
                    dialog.show(activity, "該手機還沒註冊", 1);
                    return;
                } else {
                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et.getWindowToken(), 0);

                    RegitsterCodeFragment findpwd = RegitsterCodeFragment.getInstance(String.valueOf(et.getText()), "1", "normalRegister");
                    ft = manager.beginTransaction();
                    //当前的fragment会被RegisterFragment替换
                    ft.replace(R.id.fragment_container, findpwd);
                    ft.addToBackStack(null);
                    ft.commit();
                }

            }
        }, true);

    }

    private void setBlockList(List<Map<String, Object>> list) {
        List<ContactMemberDTO> dataList = new ArrayList<>();
        for (Map<String, Object> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            dataList.add(memberDTO);
        }

        Map<String, ContactMemberDTO> maps = new HashMap<>();
        for (ContactMemberDTO memberDTO : dataList) {
            maps.put(memberDTO.getId(), memberDTO);
        }
        MyGoApplication.setBlockList(maps);
    }

    /**
     * 封鎖好友列表
     **/
    private void doBlockList() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestBlockList;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, Object>> list = (ArrayList) map.get("friends");
                    setBlockList(list);

                    //登录容联云
                    ((EntranceActivity) activity).initECLoginConfig(MyGoApplication.myECUserid);
                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:

                params.put("username", String.valueOf(et.getText()));
                params.put("password", String.valueOf(pwdEt.getText()));

                if ("".equals(String.valueOf(et.getText()))) {
                    MyAlertDialog dialog = new MyAlertDialog(activity, "請輸入賬號", String.valueOf(tv.getText()));
                    dialog.show(activity, "請輸入賬號", 0);
                    return;
                }
                if ("".equals(String.valueOf(pwdEt.getText()))) {
                    MyAlertDialog dialog = new MyAlertDialog(activity, "請輸入密碼", String.valueOf(tv.getText()));
                    dialog.show(activity, "請輸入密碼", 0);
                    return;
                }

                String count = LocalInfo.getLoginCount(activity, String.valueOf(tv.getText()));
                if ("3".equals(count)) {
                    MyAlertDialog dialog = new MyAlertDialog(activity, "", String.valueOf(tv.getText()));
                    dialog.show(activity, "", 2);
                } else {
                    httpModel.startRequest();
                }

                break;
            case R.id.btn_register:

                RegisterFragment register = RegisterFragment.getInstance("nomalRegister");
                ft = manager.beginTransaction();
                //当前的fragment会被RegisterFragment替换
                ft.replace(R.id.fragment_container, register);
                ft.addToBackStack(null);
                ft.commit();

                break;
            case R.id.ll_read_pwd:
                // img_read_pwd.getim
                boolean isread = img_read_pwd.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.bt_login_remem_no).getCurrent().getConstantState());
                if (isread) {
                    //保存密碼
                    vo = new PersonalNomalInfo();
                    vo.setName(String.valueOf(et.getText()));
                    vo.setPassword(String.valueOf(pwdEt.getText()));
                    LocalInfo.saveLoginInfo(activity, vo);

                    img_read_pwd.setImageDrawable(getResources().getDrawable(R.mipmap.bt_login_remem_ok));

                } else {
                    vo = null;
                    LocalInfo.saveLoginInfo(activity, vo);
                    img_read_pwd.setImageDrawable(getResources().getDrawable(R.mipmap.bt_login_remem_no));
                }


                break;
            case R.id.other_login:
                LoginThirdFragment thirdRegister = new LoginThirdFragment();
                ft = manager.beginTransaction();
                ft.replace(R.id.fragment_container, thirdRegister);
                ft.addToBackStack(null);
                ft.commit();
                break;
            case R.id.find_pwd:

                if ("".equals(String.valueOf(et.getText())) || !VilidateUtil.isMobile(String.valueOf(et.getText()))) {
                    MyAlertDialog dialog = new MyAlertDialog(activity, "請輸入手機號", String.valueOf(tv.getText()));
                    dialog.show(activity, "請輸入手機號", 1);
                    return;
                }
                params.put("mobile", String.valueOf(et.getText()));
                validatehttpModel.startRequest();


                break;
            case R.id.txt_direct_login:
                activity.finish();
                txtDirectLogin.setTextColor(getResources().getColor(R.color.forget_font));
                break;
            default:
                break;
        }
    }

}
